package com.voole.security.filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;

import com.voole.dao.SysActionDao;
import com.voole.dao.SysAuthorityDao;
import com.voole.dao.SysCatalogDao;
import com.voole.dao.SysResourceDao;
import com.voole.dao.SysRoleActionDao;
import com.voole.dao.SysRoleDao;
import com.voole.entity.SysAuthority;
import com.voole.entity.SysRole;
import com.voole.entity.SysUser;
import com.voole.service.IMenuService;
import com.voole.service.ISysUserService;

/**
 * 登录成功后，Spring Security 的handler处理类，
 * 如果想在登录成功后，加一点自己的处理逻辑，请写在onAuthenticationSuccess方法里
 */
public class CustomLoginHandler extends SavedRequestAwareAuthenticationSuccessHandler {
	
	@Autowired
	private SysActionDao sysActionDao;
	@Autowired
	private SysRoleDao sysRoleDao;
	@Autowired
	private SysRoleActionDao sysRoleActionDao;
	@Autowired
	private SysResourceDao sysResourceDao;
	@Autowired
	private SysCatalogDao sysCatalogDao;
	@Autowired
	private SysAuthorityDao sysAuthorityDao;
	@Autowired
	private IMenuService menuService;
	@Resource
	private ISysUserService sysuserService;
	
    public void onAuthenticationSuccess(HttpServletRequest request,  HttpServletResponse response, Authentication authentication)  throws ServletException, IOException {
    	
    	super.onAuthenticationSuccess(request, response, authentication);
    	
    	//这里可以追加开发人员自己的额外处理
    	try {
	    	SecurityContext securityContext = (SecurityContext) request.getSession().getAttribute("SPRING_SECURITY_CONTEXT");

			System.out.println("登录用户账号:" + securityContext.getAuthentication().getName());
			// 获得sessionid
			//WebAuthenticationDetails details = (WebAuthenticationDetails) securityContext.getAuthentication().getDetails();
			//System.out.println("SessionId" + details.getSessionId());
			
			String userRoleType = "没有权限";
			
			//遍历 用户 权限，获取 4级目录ID
			List<Integer> userActionIdList = new ArrayList<Integer>();
			for (GrantedAuthority ga : securityContext.getAuthentication().getAuthorities()) {
				if("ROLE_ADMIN".endsWith(ga.toString())){
					userRoleType = "管理员";
					break;//ADMIN有最大权限，不用遍历
				}
				//根据ROLE_XXX '查询' role.id '查找' 4级目录ID
				SysRole sysRole = sysRoleDao.getSysRoleByRole(ga.toString());
				List<Integer> actionIdList = sysRoleActionDao.getActionIdList(sysRole.getId());
				userActionIdList.addAll(actionIdList);//存入定义参数
				
				userRoleType = "非管理员";
			}
		
    		List<SysAuthority> menuListForUserMainPage = null;
    		if("管理员".endsWith(userRoleType)){
    			menuListForUserMainPage = menuService.getMenuList();
    			userActionIdList = sysActionDao.getColumnActionId();
    		}else if("非管理员".equals(userRoleType)){
    			//4级ID(List) '转成' 字符串参数 '查询' 上级(3级)目录ID
    			Integer[] userActionIdIntArray = userActionIdList.toArray(new Integer[]{});
    			String[]  userActionIdStrArray = changeIntegerArrayToStringArray(userActionIdIntArray);
    			String userActionIds = String.join(",", userActionIdStrArray);
    			List<Integer> userResourceIdList = sysResourceDao.getColumnResourceIdByActionId(userActionIds);
    			
    			//3级ID(List) '转成' 字符串参数 '查询' 上级(2级)目录ID
    			Integer[] userResourceIdIntArray = userResourceIdList.toArray(new Integer[]{});
    			String[]  userResourceIdStrArray = changeIntegerArrayToStringArray(userResourceIdIntArray);
    			String userResourceIds = String.join(",", userResourceIdStrArray);
    			List<Integer> userCatalogIdList = sysCatalogDao.getColumnCatalogIdByResourceId(userResourceIds);
    			
    			//2级ID(List) '转成' 字符串参数 '查询' 上级(1级)目录ID
    			Integer[] userCatalogIdIntArray = userCatalogIdList.toArray(new Integer[]{});
    			String[]  userCatalogIdStrArray = changeIntegerArrayToStringArray(userCatalogIdIntArray);
    			String userCatalogIds = String.join(",", userCatalogIdStrArray);
    			List<Integer> userAuthorityIdList = sysAuthorityDao.getColumnAuthorityIdByCatalogId(userCatalogIds);
    			
    			menuListForUserMainPage = menuService.getMenuList(userAuthorityIdList, userCatalogIdList, userResourceIdList);
    		}else if("没有权限".equals(userRoleType)){
    			menuListForUserMainPage = null;
    		}
    		
    		//Session 添加 用户可见目录
    		request.getSession().setAttribute("USERAuthoritySysCatalogSysResourceList", menuListForUserMainPage);
    		//Session 添加 用户账号信息
    		SysUser sysuserInfo = sysuserService.getSysUserByAccount(securityContext.getAuthentication().getName());
    		request.getSession().setAttribute("SECURITY_SYS_USER_INFO", sysuserInfo);
    		//Session 添加 用户 四级目录(功能)ID -> 用于页面显示按钮
    		request.getSession().setAttribute("SECURITY_SYS_USER_ACTION_IDS", userActionIdList);
		
    	} catch (Exception e) {
			
		}

    }
    
    /**
     * 将 Integer数组 转换成 String数组
     *  (Integer[] -> String[])
     */
    private String[] changeIntegerArrayToStringArray(Integer[] integerArray){
    	String[] stringArray = new String[integerArray.length];
    	for(int i=0; i<integerArray.length; i++){
    		if(integerArray[i]==null){
    			continue;
    		}
    		stringArray[i] = integerArray[i].toString();
    	}
    	return stringArray;
    }

}